

package com.xgit.iov.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgit.iov.admin.mapper.SysDataRuleMapper;
import com.xgit.iov.admin.mapper.SysMenuMapper;
import com.xgit.iov.admin.mapper.SysRoleMenuMapper;
import com.xgit.iov.admin.service.SysMenuService;
import com.xgit.iov.common.core.constant.CacheConstants;
import com.xgit.iov.common.core.constant.CommonConstants;
import com.xgit.iov.common.core.constant.enums.MenuTypeEnum;
import com.xgit.iov.common.core.entity.SysDataRule;
import com.xgit.iov.common.core.entity.SysMenu;
import com.xgit.iov.common.core.entity.SysRoleMenu;
import com.xgit.iov.common.core.model.MenuTree;
import com.xgit.iov.common.core.model.TreeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author lengleng
 * @since 2017-10-29
 */
@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

	private final SysRoleMenuMapper sysRoleMenuMapper;

	private final SysDataRuleMapper sysDataRuleMapper;

	private final CacheManager cacheManager;

	@Override
	@Cacheable(value = CacheConstants.MENU_DETAILS, key = "#roleId  + '_menu'", unless = "#result == null")
	public List<SysMenu> findMenuByRoleId(Long roleId) {
		List<SysMenu> list = baseMapper.listMenusByRoleId(roleId);
		return list;
	}

	@Override
	@Cacheable(value = CacheConstants.MENU_DETAILS, key = "#roleId  + '_datarule'", unless = "#result == null")
	public List<SysMenu> findDataRuleMenuByRoleId(Long roleId) {
		List<SysMenu> menuList =  new ArrayList<>();
		List<SysDataRule> dataRuleList = sysDataRuleMapper.findByRoleId(roleId);

		for (SysDataRule dataRule : dataRuleList){
			SysMenu menu = new SysMenu();
			menu.setId(dataRule.getId());
			menu.setParentId(dataRule.getMenuId());
			menu.setName(dataRule.getName());
			menuList.add(menu);
		}
		return menuList;
	}

	/**
	 * 级联删除菜单
	 *
	 * @param id 菜单ID
	 * @return true成功,false失败
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
	public Boolean removeMenuById(Long id) {
		// 查询父节点为当前节点的节点
		List<SysMenu> menuList = this.list(Wrappers.<SysMenu>query()
			.lambda().eq(SysMenu::getParentId, id));

		if (menuList != null && menuList.size() != 0){
			throw new IllegalArgumentException("菜单含有下级不能删除");
		}
		//清楚数据权限
		cacheManager.getCache(CacheConstants.DATARULE_DETAILS).clear();
		sysRoleMenuMapper.delete(Wrappers.<SysRoleMenu>query()
			.lambda().eq(SysRoleMenu::getMenuId, id));
		//删除当前菜单及其子菜单
		return this.removeById(id);
	}

	@Override
	@CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
	public Boolean updateMenuById(SysMenu sysMenu) {
		return this.updateById(sysMenu);
	}

	/**
	 * 构建树查询
	 */
	@Override
	public List<MenuTree> treeMenu(SysMenu sysMenu) {
		if (!sysMenu.isLazy()) {
			return TreeUtil.buildTree(baseMapper.selectList(Wrappers.<SysMenu>lambdaQuery().like(StrUtil.isNotEmpty(sysMenu.getName()),SysMenu::getName,sysMenu.getName())
				.orderByAsc(SysMenu::getSort)), CommonConstants.MENU_TREE_ROOT_ID);
		}
		return TreeUtil.buildTree(baseMapper.lazyList(sysMenu), CommonConstants.MENU_TREE_ROOT_ID);
	}

	/**
	 * 返回数据权限的树形结构
	 */
	@Override
	public List<MenuTree> dataRuleTree() {

		return TreeUtil.buildDatRuleTree(baseMapper.findAllDataRuleList(), CommonConstants.MENU_TREE_ROOT_ID);
	}

	/**
	 * 查询菜单
	 *
	 * @param all      全部菜单
	 * @param parentId 父节点ID
	 * @return
	 */
	@Override
	public List<MenuTree> filterMenu(Set<SysMenu> all, Long parentId) {
		List<MenuTree> menuTreeList = all.stream()
			.filter(vo -> MenuTypeEnum.LEFT_MENU.getType().equals(vo.getType()))
			.map(MenuTree::new)
			.sorted(Comparator.comparingInt(MenuTree::getSort))
			.collect(Collectors.toList());
		Long parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId;
		return TreeUtil.build(menuTreeList, parent);
	}
}
